package com.algorithm;

import java.util.Arrays;

/**
 * 除自身以外数组的乘积
 */
public class ProductOfArrayExceptSelf {

    public static int[] productExceptSelf(int[] nums) {
//        int[] left = new int[nums.length];
//        int[] right = new int[nums.length];
//        int product = 1;
//        for (int i = 0; i < nums.length; i++) {
//            left[i] = nums[i] * product;
//            product =left[i];
//        }
//        product = 1;
//        for (int i = nums.length-1; i >= 0; i--) {
//            right[i] = nums[i] * product;
//            product =right[i];
//        }
//        int result[]=new int[nums.length];
//        result[0]=right[1];
//        result[nums.length-1]=left[nums.length-2];
//        for (int i = 1; i < nums.length-1; i++) {
//            result[i]=left[i-1]*right[i+1];
//        }
//        return result;

        int[] result = new int[nums.length];
        Arrays.fill(result, 1);
        int product = 1;
        for (int i = 0; i < nums.length; i++) {
            result[i] = result[i] * product;
            product = nums[i] * product;
        }
        product = 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            result[i] = result[i] * product;
            product = nums[i] * product;
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4};
        int[] self = productExceptSelf(nums);
        System.out.println(self);
    }
}
